import { v4 as uuid } from 'uuid';
import { TestDataAdaptor } from './TestDataAdaptor';
import { RequestHandlerContext } from '../../../../src/core/server';
import { RequestParams, errors } from '@elastic/elasticsearch';
import { DefaultTestData } from '../result_obj/default_obj'

export class DefaultBackend  implements TestDataAdaptor{
  backend = 'Default Backend';

  createNewTestData = (name: string) => {
    const testDataId = 'testData_' + uuid();

    const TestDataObject: DefaultTestData = {
      id: testDataId,
      dateCreated: new Date().toISOString(),
      name: name,
    };

    return {
      id: testDataId,
      object: TestDataObject,
    };
  };

  //上面是需要封装的一些方法
  create = async function (context: RequestHandlerContext, testDataId: string, body: any) {
    try {
      const options: RequestParams.Index = {
        index: '.test-data',
        refresh: 'true',
        id: testDataId,
        body: body,
      };
      const esClientResponse = await context.core.elasticsearch.legacy.client.callAsCurrentUser(
        'index',
        options
      )
      return esClientResponse
    } catch (error) {
      throw new Error('Index Doc Error:' + error);
    }
  }


  get = async function (context: RequestHandlerContext, testDataId: string, body: any) {
    try {
      const options: RequestParams.Get = {
        index: '.test-data',
        id: testDataId,
        type: "_doc"
      }

      const esClientResponse = await context.core.elasticsearch.legacy.client.callAsCurrentUser(
        'get',
        options
      )
      return esClientResponse._source
    } catch (error) {
      throw new Error("GET Doc Error:" + error)
    }
  };


  //下面是具体实现
  createTestData = async function (
    context: RequestHandlerContext,
    params: { name: string }
  ) {
    try {
      const newTestData = this.createNewTestData(params.name);
      const esClientResponse = await this.create(context, newTestData.id, newTestData.object);
      return { status: 'OK', message: esClientResponse, body: esClientResponse._id };
    } catch (error) {
      throw new Error('Creating New Notebook Error:' + error);
    }
  };

  getTestData = async function (
    context: RequestHandlerContext,
    testDataId: string
  ) {
    try {
      const noteObject = await this.get(context, testDataId);
      return {
        data: noteObject
      }
    } catch (error) {
      throw new Error('Fetching Notebook Error:' + error);
    }
  };

}